# Copyright (c) 2022, hzmes and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc
from frappe.utils import cint, cstr, flt
from srm.srm.doctype.srm_server_config.srm_server_config import sync_po_onebyone, get_material_from_erp, write_erp_po_entryfield

class SRMPurchaseOrder(Document):
	@frappe.whitelist()
	def get_po_from_erp(self):
		for row_item in self.purchase_order_sub:
			get_material_from_erp(row_item.material_number)
		r = sync_po_onebyone(self.erp_billno)
		if r:
			for i in r:
				row = frappe.db.get_list('SRM Purchase Order Sub', filters = { 'po_entryid': i[2] } , ignore_permissions=True)
				if row:
					frappe.db.set_value('SRM Purchase Order Sub', row[0].name, { 'closed': i[3], 'qty': i[4], 'request_date': i[5], 'price': i[6], 'amount': i[7], 'tax_price': i[8], 'tax_rate': i[9], 'all_amount': i[10], 'tax_amount': i[11], 'freezestatus': i[15], 'terminatestatus': i[16], 'freceiveqty': i[17], 'fstockinqty': i[18], 'fremainreceiveqty': i[19], 'fremainstockinqty': i[20], 'f_wlfl': i[21], 'mpq': i[22]}, update_modified=False)		
			frappe.db.set_value('SRM Purchase Order', self.name, {'doc_closed': r[0][1], 'purchase_person': r[0][12], 'currency': r[0][13], 'fapprover': r[0][14], 'fclosestatus': '已关闭' if r[0][1] == 'B' else '未关闭'}, update_modified=False)
		else:
			pass
		self.reload()
		self.save(ignore_permissions=True)

	# 确认采购订单是否接收
	@frappe.whitelist()
	def confirm_accept_by_supplier(self, selection, reject_reason=None):
		if selection:
			self.accept_by_supplier = selection
			self.reject_reason = reject_reason
			self.save(ignore_permissions=True)
			self.reload()

	# 2023-05-22: 创展项目, 把供应商答交明细反写回云星空采购订单行字段, 由JS代码来调用
	@frappe.whitelist()
	def call_write_erp_po_entryfield(self):
		# 根据分录行构建list, 和erp_fid一起传参
		if self.erp_fid:
			entry_list = []
			for i in self.purchase_order_sub:
				if i.answer_info and i.po_entryid:
					entry_list.append({'FEntryID': i.po_entryid, 'FEntryNote': i.answer_info})
			if len(entry_list) > 0:
				write_erp_po_entryfield(erp_fid=self.erp_fid, poentryids=entry_list)
			

# 生成送货单
@frappe.whitelist()
def make_purchase_delivery_from_po(source_name, target_doc=None, args=None):
	def update_item(obj, target, source_parent):
		target.source_billtype = 'SRM Purchase Order'

	doc = get_mapped_doc(
		"SRM Purchase Order",
		source_name,
		{
			"SRM Purchase Order": {
				"doctype": "SRM Purchase Delivery",
				"field_map": {"name": "from_purchase_order"},
				"validation": {
					"doc_closed": ["=", 'B'],
				},
			},
			"SRM Purchase Order Sub": {
				"doctype": "SRM Purchase Delivery Sub",
				"field_map": {
					"material_number": "material_number",
					"material_name": "material_name",
					"name": "source_billname",
					"po_entryid": "po_entryid",
				},
				# "postprocess": update_item,
				# "condition": lambda doc: doc.closed == '未关闭',
			},
		},
		target_doc,
		ignore_permissions=True,
	)

	return doc


# 标准列表查询时，不同角色强行限制查询条件
def get_permission_query_conditions(user):
	purchase_person = frappe.get_doc('User', user).full_name
	roles = []
	for r in frappe.get_doc('User', user).roles:
		roles.append(r.role)
	# frappe.msgprint(roles)
	if ('System Manager' in roles):
		return ""
	elif ('SRM Supplier' in roles):
		return ""
	elif ('SRM Purchase Manager' in roles):
		return ""
	elif ('SRM Purchase' in roles):
		return f"""(`tabSRM Purchase Order`.purchase_person in ('{purchase_person}'))"""